#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mosquitto.h>
#include <thread> // For sleep

#define MQTT_SERVER_ADDRESS "127.0.0.1"
#define MQTT_SERVER_PORT 1883
#define MQTT_TOPIC "topic"

void on_connect(struct mosquitto *mosq, void *obj, int rc)
{
    if (rc == 0)
    {
        printf("Connected to MQTT broker\n");
        mosquitto_subscribe(mosq, NULL, MQTT_TOPIC, 0); // 订阅主题
    }
    else
    {
        fprintf(stderr, "Failed to connect to MQTT broker: %s\n", mosquitto_strerror(rc));
        exit(EXIT_FAILURE);
    }
}

void on_publish(struct mosquitto *mosq, void *obj, int mid)
{
    printf("Message published:%d\n", mid);
}

void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{
    printf("Received message: %.*s\n", (int)msg->payloadlen, (char *)msg->payload);
}

int main(int argc, char **argv)
{
    unsigned int i = 0;
    int rc;
    int protocol_version = MQTT_PROTOCOL_V5;
    struct mosquitto *mosq = NULL;

    mosquitto_lib_init(); // 初始化Mosquitto库
    mosq = mosquitto_new(NULL, true, NULL);
    if (!mosq)
    {
        fprintf(stderr, "Error: Out of memory.\n");
        return EXIT_FAILURE;
    }

    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_publish_callback_set(mosq, on_publish);
    mosquitto_message_callback_set(mosq, on_message);

    // 设置MQTT协议版本
    mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &protocol_version);
    rc = mosquitto_connect(mosq, MQTT_SERVER_ADDRESS, MQTT_SERVER_PORT, 60); // 连接到MQTT broker
    if (rc != MOSQ_ERR_SUCCESS)
    {
        fprintf(stderr, "Unable to connect to MQTT broker: %s\n", mosquitto_strerror(rc));
        return EXIT_FAILURE;
    }

    mosquitto_loop_start(mosq); // 启动MQTT客户端循环
    printf("Connected to MQTT broker\n");
    while (1)
    {
        char payload[100];
        sprintf(payload, "%08d", i++);
        rc = mosquitto_publish(mosq, NULL, MQTT_TOPIC, strlen(payload), payload, 0, false);
        if (rc != MOSQ_ERR_SUCCESS)
        {
            fprintf(stderr, "Failed to publish message: %s\n", mosquitto_strerror(rc));
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }

    mosquitto_disconnect(mosq); // 断开连接
    mosquitto_destroy(mosq); // 销毁Mosquitto对象
    mosquitto_lib_cleanup(); // 清理Mosquitto库

    return 0;
}
